import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

// 自动扫描 views 目录下所有 index.vue
const modules = import.meta.glob('@/views/**/index.vue')
// 自动扫描 views 目录下所有 route.ts 或 route.js
const routeConfigs = import.meta.glob('@/views/**/route.{ts,js}', { eager: true }) as Record<string, { default: any }>

// 定义用户角色类型
export type UserRole = 'admin' | 'customer' | 'courier'

// 获取当前用户角色（实际应用中应从登录状态或token中获取）
export const getUserRole = (): UserRole => {
  // 这里模拟从localStorage获取角色信息
  return localStorage.getItem('user_role') as UserRole || 'customer'
}

// 更改用户角色（用于测试）
export const setUserRole = (role: UserRole) => {
  localStorage.setItem('user_role', role)
}

// 检查用户是否已登录
export const isLoggedIn = (): boolean => {
  return localStorage.getItem('isLoggedIn') === 'true'
}

const routes: RouteRecordRaw[] = Object.keys(modules).map((path) => {
  // 兼容 Windows 和 Unix 路径
  const match = path.match(/\/views\/(.*?)\/index\.vue$/) || path.match(/\/views\/(.*?)\/index\.vue$/)
  let name = match ? match[1] : ''
  let routePath = name.toLowerCase() === 'home' ? '/' : `/${name.toLowerCase()}`

  // 查找 route 配置
  const configPathTs = path.replace('index.vue', 'route.ts')
  const configPathJs = path.replace('index.vue', 'route.js')
  const config = routeConfigs[configPathTs]?.default || routeConfigs[configPathJs]?.default || {}

  return {
    path: routePath,
    name: name.charAt(0).toUpperCase() + name.slice(1),
    component: modules[path],
    ...config
  }
})

// 删除以下代码块：
// 手动添加新增地址页面路由
routes.push({
  path: '/addressbook/add',
  name: 'AddAddress',
  component: () => import('@/views/addressBook/add.vue'),
  meta: {
    title: '新增地址',
    requiresAuth: true,
    roles: ['customer'],
    hideInMenu: true  // 添加这一行来隐藏导航栏中的按钮
  }
})

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫，用于权限控制
router.beforeEach((to, from, next) => {
  // 检查是否是公开路由
  const isPublicRoute = to.meta?.public === true

  // 检查用户是否已登录
  if (!isLoggedIn() && !isPublicRoute) {
    // 未登录且不是公开路由，重定向到登录页
    next({ path: '/login' })
    return
  }
  
  const currentRole = getUserRole()
  
  // 已登录用户访问登录页时，重定向到对应角色的首页
  if (to.path === '/login' && isLoggedIn()) {
    if (currentRole === 'admin') {
      next('/admin-dashboard')
      return
    } else if (currentRole === 'customer') {
      next('/customer-dashboard')
      return
    } else if (currentRole === 'courier') {
      next('/courier-dashboard')
      return
    }
  }
  
  // 处理根路径访问，根据角色重定向到对应的控制台
  if (to.path === '/') {
    // 根据角色重定向到各自的首页
    if (currentRole === 'admin') {
      next('/admin-dashboard')
      return
    } else if (currentRole === 'customer') {
      next('/customer-dashboard')
      return
    } else if (currentRole === 'courier') {
      next('/courier-dashboard')
      return
    }
  }
  
  // 如果路由没有meta或没有roles，则允许所有用户访问
  if (!to.meta?.roles) {
    next()
    return
  }
  
  // 检查用户是否有权限访问
  const allowedRoles = to.meta.roles as UserRole[]
  if (allowedRoles.includes(currentRole)) {
    next()
  } else {
    // 如果没有权限，重定向到对应角色的首页
    if (currentRole === 'customer') {
      next('/customer-dashboard')
    } else if (currentRole === 'courier') {
      next('/courier-dashboard')
    } else {
      next('/admin-dashboard')
    }
  }
})

export default router